<template>
  <div class="app-container">
    <div class="content-container">
      <!--      <div class="search-bar">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item prop="name" label="品类名称">
            <el-input v-model="queryParams.name" placeholder="请输入品类名称" clearable />
          </el-form-item>
          <el-form-item prop="code" label="品类代码">
            <el-input v-model="queryParams.code" placeholder="请输入品类代码" clearable />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="search" @click="search">搜索</el-button>
            <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>-->
      <el-card shadow="never" class="table-card">
        <div class="flex-x-between mb-10px">
          <div>
            <el-button type="success" icon="plus" @click="handleOpenDialog(null)" disabled>
              新增
            </el-button>
          </div>
        </div>
        <div class="table-card-body">
          <BasePageTable
            :table-data="tableData"
            :table-columns-data="tableColumnsData"
            :total="total"
            :loading="loading"
            row-key="id"
            :default-expand-all="false"
            @handle-query="handleChangePage"
          >
            <template #status="{ row, name }">
              <el-tag :type="ENABLE_STATUS_ENUM.ENABLED.value === row.status ? 'success' : 'info'">
                {{ getLabelByValue(ENABLE_STATUS_ENUM, row.status) }}
              </el-tag>
            </template>
            <template #logo="{ row, name }">
              <el-image style="width: 100px; height: 100px" :src="row.logo" fit="cover"></el-image>
            </template>
            <template #enable="{ row, name }">
              <el-switch
                disabled
                v-model="row.enable"
                :active-value="1"
                :inactive-value="0"
                v-if="row.level === 1"
                :before-change="() => handleSwitchStatus(row)"
              />
            </template>
            <template #operation="{ row, name }">
              <el-button link type="primary" icon="Edit" @click="handleOpenDialog(row)" disabled>
                编辑
              </el-button>
              <el-button link type="danger" icon="Delete" @click="handleDelete(row.id)" disabled>
                删除
              </el-button>
            </template>
          </BasePageTable>
        </div>
      </el-card>
      <category-form ref="categoryFormRef" @load-data="handleQuery"></category-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getLabelByValue } from "@/utils/enums";
import BasePageTable from "@/components/BasePageTable/index.vue";
import { ENABLE_STATUS_ENUM } from "@/enums/brand/BrandEnum";
import CategoryForm from "@/views/system/sys-material-category/components/category-form.vue";
import categoryApi, { SysMaterialCategoryVO } from "@/api/category/category-api";
import { arrayToTree } from "@/utils/common";
import CommonAPI from "@/api/system/common";

const loading = ref(false);
const categoryFormRef = ref();
const total = ref(0);
const queryFormRef = ref();

const queryParams = reactive<PageQuery>({
  name: "",
  code: "",
  pageNum: 1,
  pageSize: 10,
});
const tableData = ref<SysMaterialCategoryVO[]>([]);
const tableColumnsData = ref([
  {
    prop: "name",
    label: "品类名称",
    showOverflowTooltip: true,
  },
  {
    prop: "code",
    label: "品类代码",
    showOverflowTooltip: true,
  },
  {
    prop: "level",
    label: "层级",
    showOverflowTooltip: true,
  },
  {
    prop: "budgetRatio",
    label: "品类预算比例",
    showOverflowTooltip: true,
  },
  {
    prop: "floatCommissionRatio",
    label: "品类佣金比例",
    showOverflowTooltip: true,
  },
  {
    prop: "enable",
    label: "状态",
    showOverflowTooltip: true,
    customSlot: "enable", // 自定义插槽名称
  },
  {
    prop: "operation",
    label: "操作",
    width: 150,
    align: "center",
    fixed: "right",
    customSlot: "operation", // 自定义插槽名称
  },
]);
async function handleSwitchStatus(row, value) {
  try {
    await ElMessageBox.confirm("确认操作吗?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    // 用户确认后，执行切换状态的逻辑
    await categoryApi.update({
      id: row.id,
      code: row.code,
      name: row.name,
      enable: row.enable === 1 ? 0 : 1,
    });

    ElMessage.success("切换状态成功");
    handleQuery();
  } catch (e) {
    ElMessage.error("切换状态失败");
  }
}

function handleChangePage({ pageNum, pageSize }) {
  queryParams.pageNum = pageNum;
  queryParams.pageSize = pageSize;
  handleQuery();
}

function search() {
  queryParams.pageNum = 1;
  handleQuery();
}
// 查询
function handleQuery() {
  loading.value = true;
  CommonAPI.getAllMaterialCategory({
    ...queryParams.value,
    isLeaf: true,
  })
    .then((data: any) => {
      let chugui = data.data.find((item: any) => item.code === "chuGui");
      tableData.value = arrayToTree(data.data || []);
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

async function handleDelete(id) {
  const res = await ElMessageBox.confirm("确认删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });

  if (!res) return;
  loading.value = true;
  try {
    await categoryApi.delete(id);
    handleQuery();
    ElMessage.success("删除成功");
  } catch (e) {
    ElMessage.success("删除失败");
  } finally {
    loading.value = false;
  }
}

function handleOpenDialog(row) {
  categoryFormRef.value.showModal(row);
}

onMounted(async () => {
  handleQuery();
});
</script>
